package com.kaigejava.demo.business.service.grab;

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONUtil;
import com.kaigejava.demo.business.common.GlobalMap;
import com.kaigejava.demo.business.service.WebSocketService;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @BelongsProject: douyin-live-java
 * @Author: kaigejava
 * @CreateTime: 2023-11-09  16:13
 * @Description: 发送消息的基类
 * @Version: 1.0
 */
@Component
public class BaseSendMessageService {

    //实例一个session，这个session是websocket的session
    protected Session session;

    String currentTime = DatePattern.NORM_DATETIME_FORMAT.format(new Date());


    public String getNowTime() {
        return currentTime;
    }


    /**
     * 新增一个方法用于主动向客户端发送消息
     *
     * @param message 消息内容
     * @param key     用户id.类型是type+roomId+时间戳
     */
    public static void sendMessage(Object message, String key) {
        WebSocketService webSocket = GlobalMap.webSocketMap.get(key);
        if (webSocket != null) {
            try {
                //获取当前key前缀的所有，然后发送
                for (Map.Entry<String, WebSocketService> stringWebSocketServiceEntry : GlobalMap.webSocketMap.entrySet()) {
                    String type = stringWebSocketServiceEntry.getKey().split("_")[0];
                    String roomId = stringWebSocketServiceEntry.getKey().split("_")[1];
                    String typeAndRoom = type + "_" + roomId;
                    if (key.contains(typeAndRoom)) {
                        webSocket.session.getBasicRemote().sendText(JSONUtil.toJsonStr(message));
                    }
                }
                // System.out.println("【websocket消息】发送消息成功,用户=" + roomId + ",消息内容" + message.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
